package org.shj.servlet;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.shj.service.UserService;
import org.shj.service.UserServiceImpl;
import org.shj.util.StoreUtils;
import org.shj.util.StringUtils;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private UserService userService;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        userService = new UserServiceImpl();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userId = request.getParameter("userId");
		String password = request.getParameter("password");
		System.out.println("userId=" + userId + "; password=" + password);
		boolean flag = userService.isValidUser(userId, password);
		
		if(flag){
			//设置登陆成功
			request.getSession().setAttribute("isLogin", true);
			
			String sessionId = request.getSession().getId();
			System.out.println("登陆成功 ");
			System.out.println("sessionId: " + sessionId);
			
			String token = UUID.randomUUID().toString();
			System.out.println("token is " + token);
			StoreUtils.addUserSession(token, sessionId, userId);
			
			String returnUrl = request.getParameter("returnUrl");
			if(StringUtils.isEmpty(returnUrl)){
            	response.getWriter().println("只提供登陆退出操作。请设置登陆成功后需返回的 URL。");
            	return;
            }
			
			//跳转回子系统
			response.sendRedirect(returnUrl + "?token=" + token);
			
		}else{
			request.setAttribute("msg", "用户名或密码错");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
